/*
 * @Author: Clark
 * @Email: haixuanwoTxh@gmail.com
 * @Date: 2023-01-28 09:46:54
 * @LastEditors: Clark
 * @LastEditTime: 2023-01-28 11:02:00
 * @Description: file content
 */

#include "apue.h"

volatile sig_atomic_t quitflag;     // set nonzero by signal handler

static void sig_int(int signo)      // one signal handler for SIGINT and SIGQUIT
{
    if (SIGINT == signo)
    {
        printf("\ninterrut\n");
    }
    else if (SIGQUIT == signo)
    {
        quitflag = 1;
    }
}

int main(void)
{
    sigset_t newmask, oldmask, zeromask;

    if (SIG_ERR == signal(SIGINT, sig_int))
        err_sys("signal(SIGINT) error");

    if (SIG_ERR == signal(SIGQUIT, sig_int))
        err_sys("signal(SIGQUIT) error");

    sigemptyset(&zeromask);
    sigemptyset(&newmask);
    sigaddset(&newmask, SIGQUIT);

    // BLOCK SIGQUIT and save current signal mask
    if (sigprocmask(SIG_BLOCK, &newmask, &oldmask) < 0)
        err_sys("SIG_BLOCK error");

    while (0 == quitflag)
    {
        sigsuspend(&zeromask);
    }

    // SIGQUIT has been caught and is now blocked; do whatever.
    quitflag = 0;

    // Reset signal mask which unblocks SIGQUIT.
    if (sigprocmask(SIG_SETMASK, &oldmask, NULL) < 0)
    {
        err_sys("SIG_SETMASK error");
    }

    exit(0);
}
